<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <!-- Converts SQL Server 2005 Profiler XML trace file data to CSV format, similar to the profiler's grid view of traces. -->
    <!-- Author: David Luu -->
    <!-- Last updated: 02/02/2009 -->
    <!-- Version 0.1, alpha status, not working as expected. -->
    <!-- Not well documented. Use at your own risk. -->
    <!-- I could use some help with fine tuning the stylesheet to get it working the way it should. -->
    <!-- Output as CSV text and define variables -->
    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/>
    <xsl:variable name="newline" select=" '&#10;' " />
    <xsl:param name="comma"><xsl:text>,</xsl:text></xsl:param>

    <xsl:template match="TraceData">
	<xsl:apply-templates select="Header/ProfilerUI/OrderedColumns"/>
	<xsl:apply-templates select="Events//Event"/>
    </xsl:template>

    <xsl:template match="OrderedColumns">
	<xsl:for-each select="child::node()">
		<xsl:sort select="." data-type="number" order="ascending"/>
		<xsl:choose>
			<xsl:when test="self = 27">
				EventClass
				<xsl:value-of select="$newline"/>
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="/TraceData/Events/Event/Column[1][@id = self]/@name"/>
				<xsl:value-of select="$comma"/>
			</xsl:otherwise>
		</xsl:choose>
        	<xsl:choose>
			<xsl:when test="position() = last()">
				<xsl:value-of select="$newline"/>
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="$comma"/>
			</xsl:otherwise>
		</xsl:choose>
		<!-- Define header and preserve order by looking up column name using the given ID -->
	</xsl:for-each>
    </xsl:template>

    <xsl:template match="Event">
	<!-- Assume EventClass is always 1st column -->
	<xsl:value-of select="@name"/>
	<xsl:value-of select="$comma"/>
        <xsl:for-each select="child::node()">
		<xsl:sort select="@id" data-type="number" order="ascending"/>
        	<xsl:value-of select="."/>
		<xsl:choose>
			<xsl:when test="position() = last()">
				<xsl:value-of select="$newline"/>
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="$comma"/>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
